* -------------------------------------------------------------------------------
*			PROGRAM BOOTR2
*
*	residual-based bootstrap. Last updated: 10/5/23
*	same as bootr, but in our MCs I don't want to drop the first missing value. 
* -------------------------------------------------------------------------------

cap prog drop bootr2
prog define bootr2, rclass
syntax [if] [in], old(string) newname(string) [minT(string)]
* old: variable to bootstrap.
* newname: name of the bootstrapped variable
* minT: in AR models like GARCH, if missing first observation bootr2 will bootstrap 
* T-1 observed values, but when joining back will keep the t=1 missing value (needed for monte carlos)
* Basically minT just helps put __foo in the right place

* preliminaries
tempfile __bootdata
tempvar __foo
qui tsset // ensure we're tsset and sorted
qui gen `__foo' = _n

preserve
	keep `old'
	drop if `old' == .
	bsample
	if "`minT'" != "" {
		gen `__foo' = _n + (`minT'-1) // e.g., minT = 2, then __foo starts at 2. if minT = 1, __foo starts at 1
	}
	else {
		noi di in y "You should specify minT, even if minT(1)...i.e., no missing first obs"
	}
	rename `old' `newname'	
	qui save `__bootdata'
restore

qui joinby `__foo' using `__bootdata', unmatched(master)
qui drop _merge
end


/* example:

bootr, old(residual) new(bootresid)

*/
